package Master

import (
	"MserviceTask/Common"
	"log"
	"net"
	"net/http"
	"time"
)

type MHttpService struct {
	HttpServer *http.Server
}

var (
	G_HttpService *MHttpService
)

//保存
func handelSave(res http.ResponseWriter, req *http.Request) {
	res.Write([]byte("你好"))
}

//创建HTTPService
func NewMHttpService() (err error) {
	var (
		mux          *http.ServeMux
		httpServer   *http.Server
		htmlDir      http.Dir
		htmlHandler  http.Handler
		listen       net.Listener
		readTimeout  int
		writeTimeout int
	)
	mux = http.NewServeMux()
	mux.HandleFunc("/api/v1/save", handelSave)
	//mux.HandleFunc("/api/v1/task/list/", HttpServices.HandelTaskList)
	htmlDir = http.Dir(Common.G_CONF.String("HTTP.htmlRoot"))
	htmlHandler = http.FileServer(htmlDir)
	mux.Handle("/", http.StripPrefix("/", htmlHandler))

	if listen, err = net.Listen("tcp", ":"+Common.G_CONF.String("HTTP.port")); err != nil {
		goto ERR
	}
	if readTimeout, err = Common.G_CONF.Int("HTTP.ReadTimeout"); err != nil {
		goto ERR
	}
	if writeTimeout, err = Common.G_CONF.Int("HTTP.WriteTimeout"); err != nil {
		goto ERR
	}
	httpServer = &http.Server{
		ReadTimeout:  time.Duration(readTimeout) * time.Millisecond,
		WriteTimeout: time.Duration(writeTimeout) * time.Millisecond,
		Handler:      mux,
	}
	G_HttpService = &MHttpService{
		httpServer,
	}
	println("Http IS RUN 0.0.0.0 : " + Common.G_CONF.String("HTTP.port"))
	go httpServer.Serve(listen)
	return
ERR:
	log.Printf("ERR:%v", err)
	return
}
